package rbacControllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"html/template"
	"lazyops_go/models"
	"lazyops_go/tools"
)

type IndexController struct {
	beego.Controller
}

//首页访问视图
func (c *IndexController) Get() {
	cur_user_menus := c.GetSession("cur_user_menus")
	cur_user := c.GetSession("cur_user")
	c.Data["cur_user"] = cur_user
	c.Data["cur_user_menus"] = cur_user_menus
	c.Data["label"] = "Dashboard"
	c.TplName = "base/base.html"
}

func (c *IndexController) Login() {
	c.Data["xsrfdata"]=template.HTML(c.XSRFFormHTML())
	cur_user := c.GetSession("cur_user")
	err := c.GetSession("err")
	if cur_user != nil{
		// 当前已经登录
		c.Redirect("/index/",302)
		c.DelSession("err")
	}

	c.XSRFExpire = 7200
	c.Data["xsrf_token"] = c.XSRFToken()
	c.Data["err"] = err
	c.TplName = "base/login.html"
}

func (c *IndexController) DoLogin()  {
	username := c.GetString("username")
	password := c.GetString("password")
	passwd_key := c.GetString("passwd_key")
	eaes_password:= tools.DePwdCode(password,passwd_key)
	en_password := tools.Md5Encode(eaes_password)
	user,err:= models.GetUserByNameAndPwd(username,en_password)
	//记录登陆日志
	obj := models.LogUser{}
	obj.UserName = username
	obj.Req = "登陆"
	obj.ReqMenu = "用户"
	obj.ReqData = fmt.Sprintf("{\"username\":%s,\"password\":%s}",username,password)
	if err != nil {
		err := "用户或密码错误"
		obj.Status = err
		c.SetSession("err",err)
		c.Redirect("/",302)
	}else{
		if user.Status == 0 {
			err := "用户被禁用"
			obj.Status = err
			c.SetSession("err",err)
			c.SetSession("err",err)
			c.Redirect("/",302)
		}else{


			c.DelSession("err")
			obj.Status = "success"
			c.SetSession("cur_user",user.UserName)
			c.SetSession("is_super",user.IsSuper)
			//获取当前用户权限
			cur_user_roles := user.Roles

			cur_user_perms := models.GetUserPerms(cur_user_roles)
			cur_user_menus := models.GetUserMenus(cur_user_perms)

			var role_id_list []int
			for _,v :=range cur_user_roles{
				role_id_list = append(role_id_list, v.ID)
			}

			c.SetSession("role_id_list",role_id_list)

			c.SetSession("cur_user_perms",cur_user_perms)
			c.SetSession("cur_user_menus",cur_user_menus)
			c.Redirect("/index/",302)
		}
	}
	//添加登陆日志
	models.AddLogUser(obj)
}

//退出登录
func (c *IndexController) Logout(){
	c.DelSession("cur_user")
	c.Redirect("/",302)
}
